package com.rjwh.dingdong.client.player;

import android.content.Context;
import android.media.AudioManager;
import android.media.MediaPlayer;
import android.media.MediaPlayer.OnBufferingUpdateListener;
import android.media.MediaPlayer.OnPreparedListener;

import com.rjwh.dingdong.client.bean.localbean.PlayList;
import com.rjwh.dingdong.client.bean.localbean.Song;
import com.rjwh.dingdong.client.util.LogUtil;
import com.rjwh.dingdong.client.util.RxBus;


public class Player implements IPlayback, MediaPlayer.OnCompletionListener,
		OnBufferingUpdateListener, OnPreparedListener {

	private static final String TAG = "Player";

	private static volatile Player sInstance;

	private MediaPlayer mPlayer;

	private PlayList mPlayList;


	// Player status
	private boolean isPaused;

	private Context context;

	//默认状态是停止状态
	private PlayState playStatus = PlayState.STOP;

	/**
	 * Intent：用于表示广播中发送的信息
	 */
//	private Intent broadcastIntent = new Intent();

	private Player(Context context) {
		this.context = context;
		mPlayer = new MediaPlayer();
		mPlayList = new PlayList();
		mPlayer.setOnCompletionListener(this);
		mPlayer.setOnPreparedListener(this);
		mPlayer.setOnBufferingUpdateListener(this);

	}

	public static Player getInstance(Context context) {
		if (sInstance == null) {
			synchronized (Player.class) {
				if (sInstance == null) {
					sInstance = new Player(context);
				}
			}
		}
		return sInstance;
	}

	@Override
	public void setPlayList(PlayList list) {
		if (list == null) {
			list = new PlayList();
		}
		mPlayList = list;
	}

	@Override
	public PlayList getPlayList() {
		return mPlayList;
	}

	@Override
	public boolean play() {
		if (isPaused) {
			isPaused = false;
			mPlayer.start();
			playStatus = PlayState.PLAY;
			notifyPlayStatusChanged(playStatus);
			return true;
		}
		if (mPlayList.prepare()) {
			Song song = mPlayList.getCurrentSong();
			notifyComplete(song);
			mPlayer.reset();
			mPlayer.setAudioStreamType(AudioManager.STREAM_MUSIC);
			try {
				LogUtil.d("song.getAudiourl():"+song.getAudiourl());
				mPlayer.setDataSource(song.getAudiourl());
				mPlayer.prepareAsync();
				playStatus = PlayState.READY;
				notifyPlayStatusChanged(playStatus);
			} catch (Exception e) {
				e.printStackTrace();
			}
			return true;
		}
		return false;
	}

	@Override
	public boolean play(PlayList list) {
		if (list == null)
			return false;

		isPaused = false;
		setPlayList(list);
		return play();
	}

	@Override
	public boolean play(PlayList list, int startIndex) {
		if (list == null || startIndex < 0
				|| startIndex >= list.getNumOfSongs())
			return false;

		isPaused = false;
		list.setPlayingIndex(startIndex);
		setPlayList(list);
		return play();
	}

	@Override
	public boolean play(Song song) {
		if (song == null)
			return false;

		isPaused = false;
		mPlayList.getSongs().clear();
		mPlayList.getSongs().add(song);
		return play();
	}

	@Override
	public boolean playLast() {
		isPaused = false;
		boolean hasLast = mPlayList.hasLast();
		if (hasLast) {
			Song last = mPlayList.last();
			play();
			notifyPlayLast(last);
			return true;
		}
		return false;
	}

	@Override
	public boolean playNext() {
		isPaused = false;
		boolean hasNext = mPlayList.hasNext(false);
		if (hasNext) {
			Song next = mPlayList.next();
			play();
			notifyPlayNext(next);
			return true;
		}
		return false;
	}

	@Override
	public boolean pause() {
		if (mPlayer != null && mPlayer.isPlaying()) {
			mPlayer.pause();
			isPaused = true;
			playStatus =  PlayState.PAUSE;
			notifyPlayStatusChanged(playStatus);
			return true;
		}
		return false;
	}

	@Override
	public boolean stop() {
		if (mPlayer != null && mPlayer.isPlaying()) {
			mPlayer.stop();
			playStatus = PlayState.STOP;
			notifyPlayStatusChanged(playStatus);
			return true;
		}
		return false;
	}

	@Override
	public boolean isPlaying() {
		if(mPlayer != null){
			return mPlayer.isPlaying();
		}
		return false;
	}

	@Override
	public int getProgress() {
		if(mPlayer != null){
			return mPlayer.getCurrentPosition();
		}
		return 0;
	}

	public int getDuration() {
		if(mPlayer != null){
			return mPlayer.getDuration();
		}
		return 0;
	}

	@Override
	public Song getPlayingSong() {
		if(mPlayList != null){
			return mPlayList.getCurrentSong();
		}
		return null;
	}

	@Override
	public boolean seekTo(int progress) {
		if (mPlayList!=null && mPlayList.getSongs().isEmpty())
			return false;

//		Song currentSong = mPlayList.getCurrentSong();
//		if (currentSong != null) {
//			if (currentSong.getDuration() <= progress) {
//				onCompletion(mPlayer);
//			} else {
		mPlayer.seekTo(progress);
//			}
//			return true;
//		}
		return false;
	}

	@Override
	public void setPlayMode(PlayMode playMode) {
		if(mPlayList !=null)mPlayList.setPlayMode(playMode);
	}

	// Listeners

	@Override
	public void onCompletion(MediaPlayer mp) {
		Song next = null;
		// There is only one limited play mode which is list, player should be
		// stopped when hitting the list end
		if (mPlayList.getPlayMode() == PlayMode.LIST
				&& mPlayList.getPlayingIndex() == mPlayList.getNumOfSongs() - 1) {
			// In the end of the list
			// Do nothing, just deliver the callback
		} else if (mPlayList.getPlayMode() == PlayMode.SINGLE) {
			next = mPlayList.getCurrentSong();
			play();
		} else {
			boolean hasNext = mPlayList.hasNext(true);
			if (hasNext) {
				next = mPlayList.next();
				play();
			}
		}
		if(next == null){
//			playStatus = PlayState.STOP;
			stop();
//			notifyPlayStatusChanged(playStatus);
		}
		notifyComplete(next);
	}

	@Override
	public void onBufferingUpdate(MediaPlayer mp, int percent) {
		if (percent <= 100) {
//			Intent intent = new Intent();
//			intent.setAction(PlayConstants.ACTION_PLAY_SECOND_PROG);
//			intent.putExtra(PlayConstants.KEY_SECOND_PROGRESS, percent);
//			context.sendBroadcast(intent);
			RxBus.get().post(PlayConstants.ACTION_PLAY_SECOND_PROG,percent);
		}
	}

	@Override
	public void onPrepared(MediaPlayer mp) {
		mp.start();
		playStatus =  PlayState.PLAY;
		notifyPlayStatusChanged(playStatus);
	}

	@Override
	public void releasePlayer() {
		mPlayList = null;
		mPlayer.reset();
		mPlayer.release();
		mPlayer = null;
		sInstance = null;
	}


	private void notifyPlayStatusChanged(PlayState isPlaying) {

		RxBus.get().post(PlayConstants.ACTION_PLAY_STATUS_CHANGED,isPlaying);

//		broadcastIntent.setAction(PlayConstants.ACTION_PLAY_STATUS_CHANGED);
//		broadcastIntent.putExtra(PlayConstants.KEY_PLAY_STATUS_CHANGE, isPlaying);
//		context.sendBroadcast(broadcastIntent);

		if(isPlaying ==  PlayState.PLAY){
			startUpdateProgressThread();
		}
		else{
			stopUpdateProgressThread();
		}
	}

	private void notifyPlayLast(Song song) {
		RxBus.get().post(PlayConstants.ACTION_UPDATA_SONG,song);

//		broadcastIntent.setAction(PlayConstants.ACTION_UPDATA_SONG);
//		broadcastIntent.putExtra(PlayConstants.KEY_PLAY_UPDATA_SONG, song);
//		context.sendBroadcast(broadcastIntent);

	}

	private void notifyPlayNext(Song song) {
		RxBus.get().post(PlayConstants.ACTION_UPDATA_SONG,song);
//
//		broadcastIntent.setAction(PlayConstants.ACTION_UPDATA_SONG);
//		broadcastIntent.putExtra(PlayConstants.KEY_PLAY_UPDATA_SONG, song);
//		context.sendBroadcast(broadcastIntent);
	}

	private void notifyComplete(Song song) {
		RxBus.get().post(PlayConstants.ACTION_UPDATA_SONG,song);
//		broadcastIntent.setAction(PlayConstants.ACTION_UPDATA_SONG);
//		broadcastIntent.putExtra(PlayConstants.KEY_PLAY_UPDATA_SONG, song);
//		context.sendBroadcast(broadcastIntent);
	}

	@Override
	public PlayState getPlayStatus() {
		// TODO Auto-generated method stub
		return playStatus;
	}

	/**
	 * 更新进度的线程
	 */
	private UpdateProgressThread updateProgressThread;

	/**
	 * 开启更新进度(发送广播让Activity更新)的线程
	 */
	private void startUpdateProgressThread() {
		if (updateProgressThread == null) {
			updateProgressThread = new UpdateProgressThread();
			updateProgressThread.setRunning(true);
			updateProgressThread.start();
		}
	}

	/**
	 * 停止更新进度(发送广播让Activity更新)的线程
	 */
	private void stopUpdateProgressThread() {
		if (updateProgressThread != null) {
			updateProgressThread.setRunning(false);
			updateProgressThread = null;
		}
	}

	private class UpdateProgressThread extends Thread {
		private boolean isRunning;

		public void setRunning(boolean isRunning) {
			this.isRunning = isRunning;
		}

		@Override
		public void run() {
			while (isRunning) {
				if (mPlayer !=null && mPlayer.isPlaying()) {

					RxBus.get().post(PlayConstants.ACTION_PLAY_PROG,getProgress());

//					// 发出广播：使Activity更新播放进度
//					broadcastIntent.setAction(PlayConstants.ACTION_PLAY_PROG);
//					broadcastIntent.putExtra(PlayConstants.KEY_PLAY_PROGRESS, getProgress());
//					context.sendBroadcast(broadcastIntent);
				}

				try {
					Thread.sleep(500);
				} catch (InterruptedException e) {
					e.printStackTrace();
				}
			}
		}
	}
}
